package com.imooc.security.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/users")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public void login(@Validated UserInfo user , HttpServletRequest request){
        UserInfo userInfo = userService.login(user);
        request.getSession().setAttribute("user",userInfo);

    }

    @PostMapping
    public UserInfo create(@RequestBody @Validated UserInfo user){
        return userService.create(user);
    }

    @PutMapping("{id}")
    public UserInfo update(@RequestBody UserInfo user){
        return userService.update();
    }

    @DeleteMapping("{id}")
    public void delete(@RequestBody Long id){
        userService.delete(id);
    }

    @GetMapping("{id}")
    public UserInfo get(@PathVariable Long id , HttpServletRequest request) throws IOException {
        User user = (User) request.getAttribute("user");

        if(user == null || !user.getId().equals(id)){
            throw new RuntimeException("身份认证信息异常，获取用户信息失败");
        }
        return userService.get(id);
    }

    @GetMapping
    public List<UserInfo> query(String name){
//        String sql = "select id,name from user where name ='"+name+"'";
//        return userRepository.findByName(name);
          return userService.findByName(name);
    }
}
